#include "D_Input.h"
#include "Definitions.h"

extern HINSTANCE g_hInst;
extern HWND g_wndHandle;

D_Input::D_Input()
{
	DirectInput8Create(g_hInst, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_pDIObject, NULL);

	m_pDIObject->CreateDevice(GUID_SysKeyboard, &m_pDIKeyboard, NULL);
	m_pDIObject->CreateDevice(GUID_SysMouse, &m_pDIMouse, NULL);

	m_pDIKeyboard->SetCooperativeLevel(g_wndHandle, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
	m_pDIMouse->SetCooperativeLevel(g_wndHandle, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
	
	m_pDIKeyboard->SetDataFormat(&c_dfDIKeyboard);
	m_pDIMouse->SetDataFormat(&c_dfDIMouse2);

	mHidden = false;

	Update();
	hideCursor();
	showCursor();
}

bool D_Input::Update()
{
	m_pDIKeyboard->Acquire();
    m_pDIKeyboard->GetDeviceState(sizeof(keyBuffer), (LPVOID)&keyBuffer);
	if(keyBuffer[DIK_ESCAPE] & 0x80)	return false;

    m_pDIMouse->Acquire();
	m_pDIMouse->GetDeviceState(sizeof(DIMOUSESTATE2), &mouseState);

	info.Clicked = (mouseState.rgbButtons[0] & 0x80);

	if(info.Clicked)
		info.MeterMod = (int)(meterYsensitivity*mouseState.lY);
	else
		info.MeterMod = (int)(meterZsensitivity*mouseState.lZ);

	if(mHidden)
	{
		SetCursorPos(stuckPosP.x, stuckPosP.y);
		info.pos = stuckPosXY;
	}
	else
	{
		POINT point;
		GetCursorPos(&point);
		ScreenToClient(g_wndHandle, &point);
		info.pos = point;
	}

	return true;
}

void D_Input::hideCursor()
{
	ShowCursor(mHidden);
	mHidden = true;

	POINT point;
	GetCursorPos(&point);
	stuckPosP = point;

	ScreenToClient(g_wndHandle, &point);
	stuckPosXY = point;
}

void D_Input::showCursor()
{
	ShowCursor(mHidden);
	mHidden = false;
}